/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.unipar.cursoweb.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
 *
 * @author Thiago
 */
@FacesValidator("validadorCPF")
public class ValidadorCPF implements Validator {

    private static final int[] pesoCPF = {11, 10, 9, 8, 7, 6, 5, 4, 3, 2};

    @Override
    public void validate(FacesContext context, UIComponent component, Object obj) throws ValidatorException {
        String cpf = (String) obj;
        if (!isValidCPF(cpf)) {
            FacesMessage message = new FacesMessage();
            message.setSummary("CPF inválido");
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(message);
        }
    }

    public static boolean isValidCPF(String cpf) {
        if (cpf.equals("") || cpf == null) {
            return true;
        }
        Boolean cpfValido = false;
        Integer digito1 = calcularDigito(cpf.substring(0, 9), pesoCPF);
        Integer digito2 = calcularDigito(cpf.substring(0, 9) + digito1, pesoCPF);
        cpfValido = cpf.equals(cpf.substring(0, 9) + digito1.toString() + digito2.toString());
        return cpfValido;
    }

    private static int calcularDigito(String str, int[] peso) {
        int soma = 0;
        for (int indice = str.length() - 1, digito; indice >= 0; indice--) {
            digito = Integer.parseInt(str.substring(indice, indice + 1));
            soma += digito * peso[peso.length - str.length() + indice];
        }
        soma = 11 - soma % 11;
        return soma > 9 ? 0 : soma;
    }
}
